package org.example;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import bean.DB;
import bean.ResponseUtils;

@WebServlet("/updateProfileServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class updateProfileServlet extends HttpServlet {

    // 头像上传的存储路径，修改为绝对路径
    private static final String UPLOAD_DIRECTORY = "C:\\Users\\DELL\\IdeaProjects\\productsManagerSys\\src\\main\\webapp\\image\\user";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取用户ID
        String userId = (String) request.getSession().getAttribute("userId");
        if (userId == null) {
            ResponseUtils.sendResponse(response, "请先登录！", "login.jsp");
            return;
        }

        String newAvatarPath = null;

        // 处理头像上传
        try {
            Part filePart = request.getPart("newAvatar");
            if (filePart != null && filePart.getSize() > 0) {
                // 修改为你指定的绝对路径
                File uploadDir = new File(UPLOAD_DIRECTORY);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs(); // 如果文件夹不存在，则创建
                }

                // 获取文件名并保存
                String fileName = Path.of(filePart.getSubmittedFileName()).getFileName().toString();
                String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                try (InputStream fileContent = filePart.getInputStream()) {
                    Files.copy(fileContent, Path.of(filePath), StandardCopyOption.REPLACE_EXISTING);
                }

                // 生成相对路径存储到数据库
                newAvatarPath = "image/user/" + fileName;
            } else {
                ResponseUtils.sendResponse(response, "未选择头像文件，请重新上传。", "userinfo.jsp");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "头像上传失败：" + e.getMessage(), "userinfo.jsp");
            return;
        }

        // 更新数据库中的头像路径
        DB db = new DB();
        try {
            String sql = "UPDATE users SET user_avatar = ? WHERE id = ?";
            try (var conn = db.createConn();
                 var ps = conn.prepareStatement(sql)) {
                ps.setString(1, newAvatarPath);
                ps.setString(2, userId);

                int rowsUpdated = ps.executeUpdate();
                if (rowsUpdated > 0) {
                    ResponseUtils.sendResponse(response, "头像更新成功！", "userinfo.jsp");
                } else {
                    ResponseUtils.sendResponse(response, "头像更新失败，请稍后重试。", "userinfo.jsp");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库错误：" + ex.getMessage(), "userinfo.jsp");
        } finally {
            db.close(); // 手动关闭 DB 对象
        }
    }
}
